package top.javajianghu.utils;

/**
 * @author sintang
 * @date 2020-09-15 14
 */
public class TedisMsgUtils {

    public static byte[] buildCommandBody(String cmd, String... args) throws Exception {
        StringBuilder builder = new StringBuilder();
        //*[num]
        builder.append('*')
                //命令数（1） + 参数的个数
                .append(1 + args.length);
        appendCrLf(builder)
                //命令长度  $[cmd_length]
                .append("$")
                .append(cmd.length());
        appendCrLf(builder)
                //命令内容 cmd
                .append(cmd);
        appendCrLf(builder);
        //遍历参数，按照 $[num]\r\n[content]\r\n的格式拼接
        for (String arg : args) {
            builder.append("$")
                    .append(arg.length());
            appendCrLf(builder)
                    .append(arg);
            appendCrLf(builder);
        }
        System.out.println("发送消息："+builder.toString());
        return builder.toString().getBytes("UTF-8");
    }

    private static StringBuilder appendCrLf(StringBuilder builder) {
        return builder.append("\r\n");
    }
}
